package com.core.gig.web.action;

import java.util.Collections;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.core.as.ASException;
import com.core.gig.as.ASCusto;
import com.core.gig.as.ASFactory;
import com.core.gig.dto.DespesaDTO;
import com.core.gig.util.GIGUtil;

/**
 * @author Lucas Ceni
 *
 */
public class DespesaFixaAction
		extends GIGAction
{
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		return inicial(mapping, form, request, response);
	}
	
	public ActionForward inicial(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		clearForm(form);
		
		try
		{
			ASCusto asCusto = ASFactory.getInstance().getASCusto();
			request.setAttribute("despesas", asCusto.listarDespesas());
			request.setAttribute("totalDespesas", asCusto.calcularTotalDespesas());
		}
		catch (ASException e)
		{
			request.setAttribute("despesas", Collections.EMPTY_LIST);
			addMessage(request, e.getMessage(), ICO_ERROR);
		}
		return mapping.findForward(FWD_DEFAULT);
	}
	
	public ActionForward incluir(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		DespesaDTO dto = new DespesaDTO();
		GIGUtil.copyProperties(dto, form);
		
		try
		{
			ASCusto asCusto = ASFactory.getInstance().getASCusto();
			asCusto.salvarDespesa(dto);
			
			addMessage(request, "global.msg.sucess.inclusion", ICO_OK);
		}
		catch (ASException e)
		{
			addMessage(request, e.getMessage(), ICO_ERROR);
		}
		return inicial(mapping, form, request, response);
	}
	
	public ActionForward excluir(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		int id = id(form);
		
		DespesaDTO dto = new DespesaDTO();
		dto.setId(id);
		
		try
		{
			ASCusto as = ASFactory.getInstance().getASCusto();
			as.excluirDespesa(dto);
			addMessage(request, "global.msg.sucess.exclusion", ICO_OK);
		}
		catch (ASException e)
		{
			addMessage(request, e.getMessage(), ICO_ERROR);
		}
		return inicial(mapping, form, request, response);
	}
}